package com.jsyso.weixin.api;

import org.apache.commons.lang3.StringUtils;

import com.jsyso.jsyso.json.jackson.JsonMapper;
import com.jsyso.jsyso.util.CastUtils;
import com.jsyso.jsyso.util.JsMap;
import com.jsyso.weixin.utils.XML;

/**
 * 响应内容
 * @author janjan, xujian_jason@163.com
 *
 */
public class Response {

	private JsMap attrs;
	private String content;
	
	public Response(String content, ResponseType responseType) {
		this.content = content;
		if(responseType == ResponseType.JSON) 
			this.parseJson();
		else if(responseType == ResponseType.XML)
			this.parseXml();
	}
	
	public boolean isEmpty() {
		return this.attrs == null || this.attrs.isEmpty();
	}
	
	protected void parseJson() {
		if(StringUtils.isNotBlank(this.content))
			this.attrs = JsonMapper.getInstance().fromJson(content, JsMap.class);
	}
	
	protected void parseXml() {
		if(StringUtils.isNotBlank(this.content))
			this.attrs = XML.xmlToMap(this.content);
	}
	
	public Object get(Object key) {
		return attrs.get(key);
	}

	public <T> T get(Object key, Class<T> clazz) {
		Object value = attrs.get(key);
		return CastUtils.cast(value, clazz);
	}
	
	public Integer errcode() {
		return this.attrs == null ? -1 : (this.attrs.containsKey("errcode") 
				? get("errcode", Integer.class) : 0);
	}
	
	public String errmsg() {
		return this.attrs == null ? "请求异常，请重试" : (this.attrs.containsKey("errmsg") 
				? get("errmsg", String.class) : "");
	}
	
	public boolean isSuccess() {
		return errcode() == 0;
	}
	
	public JsMap getAttrs() {
		return attrs;
	}
	
	public String getContent() {
		return content;
	}
	
	@Override
	public String toString() {
		return this.content;
	}
}
